package com.itruth.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.itruth.dao.ShareDao;
import com.itruth.entity.ShareEntity;
import com.itruth.util.ConnUtil;
import com.itruth.util.Constant;

public class ShareDaoImpl implements ShareDao{
	
	public List<ShareEntity> query(int shareDataId, boolean pullDownRefresh) throws SQLException {
		
		List<ShareEntity> shares = new ArrayList<ShareEntity>();
		
		String sql = null;
		
		if (pullDownRefresh) {
			sql = "select * from share order by id desc limit 0, "  + Constant.COUNT_EVERY_PAGE;
		} else {
			sql = "select * from share where id < ? order by id desc limit 0, "  + Constant.COUNT_EVERY_PAGE;
		}
		
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = ConnUtil.getConn();
			ps = conn.prepareStatement(sql);
			
			if (!pullDownRefresh) {
				ps.setInt(1, shareDataId);
			}
			
			ResultSet rs = ps.executeQuery();
			
			ShareEntity entity = null;
			while (rs.next()) {
				entity = new ShareEntity();
				entity.setId(rs.getInt("id"));
				entity.setContent(rs.getString("content"));
				entity.setAuthor(rs.getString("author"));
				entity.setShareTime(rs.getTimestamp("share_time"));
				shares.add(entity);
			}
			
		} finally {

			try {
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return shares;
		
	}
	
	public void insert(ShareEntity shareEntity) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = ConnUtil.getConn();
			ps = conn.prepareStatement("insert into share(content, add_time, username) values (?, ?, ?)");
			
			ps.setString(1, shareEntity.getContent());
			ps.setTimestamp(2, shareEntity.obtainShareTime());
			ps.setString(3, shareEntity.getAuthor());
			ps.executeUpdate();
			
		} finally {

			try {
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
